package com.leyou.item.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.dto.pojo.CategoryDTO;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.pojo.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 分类service
 *
 * @author xxx
 */
@Service
public class CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    public List<CategoryDTO> queryListByParent(Long pid) {
        // 1. 创建对象
        Category category = new Category();
        // 2. 设置pid
        category.setParentId(pid);
        // 3. 根据category查询数据库
        List<Category> categoryList = categoryMapper.select(category);
        // 4. 判断结果
        if (CollectionUtils.isEmpty(categoryList)) {
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        // 5. 使用自定义工具，把categoryList转为List<CategoryDTO>
        return BeanHelper.copyWithCollection(categoryList, CategoryDTO.class);
    }

    public List<CategoryDTO> queryByIds(List<Long> categoryIds) {
        // 查询分类
        List<Category> categoryList = categoryMapper.selectByIdList(categoryIds);
        if (CollectionUtils.isEmpty(categoryList)) {
            throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
        }
        // 转为dto
        return BeanHelper.copyWithCollection(categoryList, CategoryDTO.class);
    }
}
